package com.woniu108.valueAdded.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.woniu108.carService.commons.log.AdminHistoryLog;
import com.woniu108.carService.commos.dto.UserVipDto;
import com.woniu108.carService.commos.exception.WoniuException;
import com.woniu108.carService.commos.model.Result;
import com.woniu108.carService.commos.util.JWTUtil;
import com.woniu108.carService.commos.util.QRUtil;
import com.woniu108.carService.commos.util.RedisKey;
import com.woniu108.carService.commos.util.RedisUtil;
import com.woniu108.valueAdded.client.PersonClient;
import com.woniu108.valueAdded.model.UserVip;
import com.woniu108.valueAdded.service.UserVipService;
import com.woniu108.valueAdded.service.VipLevelFormService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.catalina.User;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * <p>
 * vip信息表 前端控制器
 * </p>
 *
 * @author yanxi
 * @since 2024-05-23
 */
@RestController
@RequestMapping("/userVip")
@Api(tags = "会员信息接口")
public class UserVipController {

    @Resource
    private UserVipService userVipService;
    @Resource
    private VipLevelFormService vipLevelFormService;
    @Resource
    private RedisUtil redisUtil;

    public String getUserId(String token){
        String refreshToken=redisUtil.getString(token);
        String userId= JWTUtil.parseUserToken(refreshToken).get("userId").toString();
        return userId;
    }



    /**
     * 根据用户编号获取用户vip详细信息
     * @param userId 用户ID
     * @return UserVipDto 用户vip详细信息
     */
    @GetMapping("/getUserVipInfo/{userId}.c")
    @ApiOperation("根据用户编号获取用户vip详细信息")
    @ApiImplicitParam(name = "userId",value = "用户ID")
    public Result<UserVipDto> getUserVipInfo(@PathVariable("userId")String userId){
        UserVip userVip = userVipService.getById(userId);
        if(ObjectUtil.isEmpty(userVip)) throw new WoniuException("非vip用户",10001);
        if(userVip.getVipEndTime().compareTo(LocalDateTime.now())<0) throw new WoniuException("会员已过期",10001);
        UserVipDto userVipDto = BeanUtil.toBean(userVip, UserVipDto.class);
        userVipDto.setVipLevelName(vipLevelFormService.getById(userVip.getVipLevelId()).getVipLevelName());
        return Result.getResult(UserVipDto.class).setData(userVipDto);
    }

    /**
     * 用户购买vip
     * @param token
     * @param number 购买月数
     * @return pay 前端支付网页
     */
    @GetMapping("/payVip.c")
    @ApiOperation("用户购买vip")
    @ApiImplicitParam(name = "number",value = "购买月数")
    public Result<String> payVip(@RequestHeader String token,Integer number) throws Exception {
        String userId = this.getUserId(token);
        if(userId==null) throw new WoniuException("用户不存在",10001);
        String pay=userVipService.payVip(userId,number);
        return Result.getResult(String.class).setData(pay);
    }

    /**
     * 支付宝回调
     * 成功支付则开启用户定时检测vip天数功能,未过期情况下每30天循环补充免费次数
     * @param request
     * @return 是否成功支付
     * @throws Exception
     */
    @PostMapping("/notify")
    @ApiOperation("支付宝回调接口")
    public String PayNotify(HttpServletRequest request) throws Exception{
        //异步回调主要代码
        //获取支付宝POST过来的反馈信息
        //在控制层从request取出支付宝传过来的参数
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        userVipService.payNotify(params);
        return "SUCCESS";
    }

    /**
     * 增加vip天数
     * @param userId 用户编号
     * @param vipDate 增加vip天数
     * @param isGift 是否为赠送天数,用户的vip仅有赠送天数时不享受洗车免费次数
     * @return result 是否正常访问接口结果
     */
    @GetMapping("/addUserVipDate.api")
    @ApiOperation("增加vip天数")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId",value = "用户ID"),
            @ApiImplicitParam(name = "vipDate",value = "增加vip天数"),
            @ApiImplicitParam(name = "isGift",value = "是否为赠送天数")
    })
    public Result addUserVipDate(String userId,Integer vipDate,Boolean isGift){
        userVipService.addUserVipDate(userId,vipDate,isGift);
        return Result.getResult().setMsg("增加vip天数成功");
    }

    /**
     * 赠送用户7天会员,用户的vip仅有赠送天数时不享受洗车免费次数,每个账号仅一次
     * @param userId 用户Id
     * @return result 是否正常访问接口结果
     */
    @GetMapping("/userVipAdd7Days.api")
    @ApiImplicitParam(name = "userId",value = "用户ID")
    @ApiOperation("赠送7天会员")
    @AdminHistoryLog
    public Result userVipAdd7Days(String userId){
        String str = redisUtil.getString(RedisKey.freeVip(userId));
        if("yes".equals(str)) throw new WoniuException("已向该用户赠送过7天会员试用,不可再次赠送",10001);
        Result result = this.addUserVipDate(userId, 7, true);
        redisUtil.setString(RedisKey.freeVip(userId),"yes");
        if(result.getCode()!=200) throw new WoniuException(result.getMsg(),result.getCode());
        return Result.getResult().setMsg("赠送7天会员成功");
    }

    /**
     * 扣减免费次数
     * @param userId 用户编号
     * @return result 是否正常访问接口结果
     */
    @GetMapping("/reduceFreeNum.c")
    @ApiOperation("扣减一次免费洗车次数")
    @ApiImplicitParam(name = "userId",value = "用户ID")
    public Result reduceFreeNum(String userId){
        UserVip userVip = userVipService.getById(userId);
        if(ObjectUtil.isEmpty(userVip)||userVip.getFreeNum()<=0) throw new WoniuException("非会员或无可用免费次数",10001);
        userVip.setFreeNum(userVip.getFreeNum()-1);
        userVipService.updateById(userVip);
        return Result.getResult().setMsg("扣减免费次数成功");
    }
}

